import sys
import random
import struct

from socket import socket, AF_INET, SOCK_STREAM

server_ip = sys.argv[1]
server_port = int(sys.argv[2])
Lmin = int(sys.argv[3])
Lmax = int(sys.argv[4])

def split_file(filename, Lmin, Lmax):
    with open(filename, 'r') as f:
        content = f.read().replace('\n', '')  # 读取文件内容并忽略换行符
    chunks = []
    remaining = len(content)
    while remaining > 0:
        size = min(random.randint(Lmin, Lmax), remaining)
        chunks.append(content[-size:])  # 从末尾开始分割
        content = content[:-size]
        remaining -= size
    return chunks[::-1]  # 反转列表以保持原始顺序

def send_init(sock, chunk_count):
    packet = struct.pack('>HI', 1, chunk_count)
    sock.sendall(packet)

with socket(AF_INET, SOCK_STREAM) as sock:
    sock.connect((server_ip, server_port))
    chunks = split_file('input.txt', Lmin, Lmax)
    send_init(sock, len(chunks))

    # 接收同意报文
    resp = sock.recv(2)
    if struct.unpack('>H', resp)[0] != 2:
        raise Exception("协议错误")

    # 发送数据块并接收反转结果
    reversed_chunks = []
    for i, chunk in enumerate(chunks):
        # 发送请求
        packet = struct.pack('>HI', 3, len(chunk)) + chunk.encode()
        sock.sendall(packet)

        # 接收响应
        header = sock.recv(6)
        type_, length = struct.unpack('>HI', header)
        if type_ != 4:
            raise Exception("协议错误")
        data = sock.recv(length).decode()
        print(f"第{i + 1}块: {data}")
        reversed_chunks.append(data)

    # 保存最终文件
    with open('reversed.txt', 'w') as f:
        f.write(''.join(reversed_chunks[::-1]))  # 反转最终的块列表以确保内容是原文件的反转